const crypto = require('crypto');
 
module.exports = () => {
    const appKey = 'rDMscjKqQla5';
    const appSecret = 'EI1kbOoJnz1QY72kHjNzrH5sULWlWA41fQTYMAyId3gHqsrdlD';
    return async (ctx, next) => {
        const uappKey = ctx.get('Authorization');
        if (appKey !== uappKey) {
            throw Error(ctx.__('appKey is error'));
        }
        const timestamp = ctx.query.timestamp || ctx.request.body.timestamp;
        const sign = ctx.query.sign || ctx.request.body.sign;
        const nowts = Math.floor(Date.now() / 1000);
        if (!timestamp || timestamp < nowts - 3600*2 || timestamp > nowts + 3600) {
            throw Error(ctx.__('api request expire'));
        }
        const params = { ...ctx.query, ...ctx.request.body };
        delete params.sign;
        const sortField = Object.keys(params).sort();
        let paramstr = '';
        for (let i = 0; i < sortField.length; i++) {
            paramstr += (sortField[i] + params[sortField[i]]);
        }
        paramstr = appKey + paramstr + appSecret;
        console.log(paramstr);
        const nsign = crypto.createHash('sha1').update(paramstr).digest('hex');
        if (sign !== nsign) {
            throw Error(ctx.__('sign is error'));
        } 
        await next();
    }
}